<?php
/**
 * Created by PhpStorm.
 * User: chunmeng_jiang
 * Date: 16-3-1
 * Time: 下午2:00
 */

namespace App\Eloquent;

use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\ProfitRole;
use App\Admin\Eloquent\GiftReceive;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\OrganizationalUser;
use App\Eloquent\User;
use CreateP2pHostingBorrowingTarget;
use DB;
use Log;

/**
 * @property string name
 * @property string message
 * @property string r_rate
 * @property string rate
 */
class Projects extends Model
{
    protected $fillable = [
        "financier_id","financier_id","financier_name","projects_name","finance_range","finance_money","financed_money",
        "gift_check","gift_cate","gift_money_auto","collateral_id","new_projects","project_type_template_id","sn",
        "finance_time_cate","finance_time_num","finance_rule_money","finance_rule_fold","collateral_type",
        "collateral_code","full_code","full_num","start_time","end_time","profits_cate","rate","collateral",
        "collateral_tmp","is_plan","repayment","invest_cate","status","sort","published_at","auto_rate","is_notice",
        "notice_id","notice_time","collateral_licence_no","projects_file","interest_at","trade_repayment_date"
    ];
    /**
     * @param null $cate
     * @param null $projects_code
     * @return mixed
     */
    public static function getProjects($cate=null,$projects_code=null){
        if($cate=='beginners'){
            $projects=Projects::join('codes','codes.code','=','repayment')
                ->where('new_projects',1)
                ->orderBy('created_at','desc')
                ->limit('2')
                ->select('codes.name as repayment_name','projects.*')
                ->get();
            if($projects->count()){
                $r_projects=Projects::getalltail($projects);
                return $r_projects;
            }
            return $projects;
        }
        //精选项目
        if($cate=='projects'){
            $status=array('rush','full','payment','finish','late','fail');
            $projects=Projects::join('codes','codes.code','=','repayment')
                ->whereIn('projects_code',$projects_code)
                ->where('new_projects',0)
                ->whereIn('status',$status)
                ->orderBy('sort','asc')
                ->select('codes.name as repayment_name','projects.*')
                ->get();
            return $projects;
        }
    }
    /*
     * 获取单个项目投资详情
     */
    public function getOneTail(){
        $data=ProjectsUser::where('projects_id','=',$this->id)->get();
        return $data;
    }
    /*
     * 获取单个项目
     */
    public static function getOneProjects($id){
        $status=array('rush','full','payment','finish','late','fail');
        $data=Projects::where('id','=',$id)
            ->whereIn('status',$status)
            ->first();
        return $data;
    }
    /*
     * 获取项目的投资人数和已投金额
     * $projects为一组对像
     */
    public static function getalltail($projects){
        foreach ($projects as $project) {
            $projects_id[] = $project->id;
            $project->detail = null;
            $project->had_money = 0.00;
            $project->ratio = 0.00;
            $project->user_num = '0';
            if ($project->finance_time_cate == 'd') {
                $project->finance_time_cate = '天';
            } elseif ($project->finance_time_cate == 'm') {
                $project->finance_time_cate = '自然月';
            } elseif($project->finance_time_cate == 'y') {
                $project->finance_time_cate = '年';
            } elseif($project->finance_time_cate == 'mm'){
                $project->finance_time_cate = '个月';
            }

            //担保机构用户
            $project->collateral_tmp='3';

            $collateral = Information::where('id', '=', $project->collateral_tmp)
                ->first();
            $project->collateral = $collateral->title;

            $project->invest_cate;//凭证模板

            $r_projects[$project->id] = $project;
            $r_details[$project->id] = array();
        }
        //获取该组项目的所有投资详细
        $details = ProjectsUser::whereIn('projects_id', $projects_id)
            ->get();
        //把投资详细分组
        foreach ($details as $detail) {
            $r_details[$detail->projects_id][$detail->id] = $detail;
        }
        foreach ($r_details as $key => $r_detail) {
            $money = array();
            foreach ($r_detail as $one_detail) {
                $money[] = $one_detail->invest_money;
            }
            $user_num = collect($money)->count();
            $add_money = $r_projects[$key]->financed_money;
            $finance_money = $r_projects[$key]->finance_money;
            if($finance_money>=10000){
                $r_projects[$key]->money=$finance_money/10000;
                $r_projects[$key]->money_cate='万';
            }
            else{
                $r_projects[$key]->money=number_format($finance_money,2);
                $r_projects[$key]->money_cate='元';
            }

            //项目融资详情
            $r_projects[$key]->detail = $r_detail;
            //项目融资比例
            $r_projects[$key]->r_ratio =number_format(($add_money*100/ $finance_money),2) ;//格式0.00;
            $r_projects[$key]->ratio = round($add_money*100/ $finance_money,2);//格式0.00;
            //项目还需投资金额
            $r_projects[$key]->need_money=number_format($finance_money-$add_money,2);
            //项目起投金额
            $r_projects[$key]->finance_rule_money=number_format($r_projects[$key]->finance_rule_money,2);
            //融资总金额
            $r_projects[$key]->r_finance_money=$finance_money;
            $r_projects[$key]->finance_money=number_format($finance_money,2);
            //项目已投人数
            $r_projects[$key]->user_num = $user_num;
            //项目已融资金额
            $r_projects[$key]->had_money =number_format($add_money,2) ;

        }
        return $r_projects;
    }
    /**
     * 查看项目状态
     */
    public function status(){
        return Code::findByCodeAndTypeId($this->status, 'project_status');
    }
    /**
     * 查看担保公司
     * @return [type] [description]
     */
    public function suretyCompany(){
        return OrganizationalUser::where('user_id',$this->collateral_id)->first();
    }
    /**
     * 查看担保方式
     * @return [type] [description]
     */
    public function suretyWay(){
      return Code::findByCodeAndTypeId($this->collateral, 'promise_type');
    }
    /**
     * 查看还本方式
     * @return [type] [description]
     */
    public function repayment(){
        return Code::findByCodeAndTypeId($this->repayment, 'profits_mode');
    }
    /**返回预期收益
     * @param float $money
     * @return mixed
     */
    public function getProfit(float $money=0)
    {
        if(!$money){$money=0;}
        return $this->makeList($this->getProfit1($money));
    }
    public function getProfit1(float $money){
        //查询分润各阶段投资人的总收益率
        $profit_rule = ProfitRole::where('profit_id', $this->profits_cate)//分润id
        ->where('role', 'User')//投资人
        ->sum('scale');
        $profit = $money * $profit_rule / 100;//年收益总金额
        //查询该项目的类型(月标还是天标，还本方式)
        switch($this->finance_time_cate){

            //“天”标
            case 'd':
                //每天收益
                $d_profit = $profit ;
                //取小数后两位
                $d_profit = floor($d_profit * 100) ;
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num/ 360/ 100;
                //期数：30天一期
                $month = floor($this->finance_time_num / 30)+1;
                //分期的收益(整期收益,剩余收益)
                $lists_profit=array($d_profit/ 360* 30/100,$d_profit/ 360 * ($this->finance_time_num % 30)/100);
                break;

            //“月”标
            case 'mm':
                //每月收益
                $d_profit = $profit / 12;
                //取小数后两位
                $d_profit = floor($d_profit * 100) / 100;
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num;
                //期数：每月一期
                $month=$this->finance_time_num;
                //分期收益(每月收益)
                $lists_profit=array($d_profit,$profit-($d_profit*$month));
                break;

            //“自然月”标
            case 'm':
                //每天收益
                $d_profit = $profit ;
                //取小数后两位
                $d_profit = floor($d_profit * 100) ;
                //$profit:该项目投资金额的实际收益
                $profit = $d_profit * $this->finance_time_num*30/ 360/ 100;
                //期数：30天一期
                $month = $this->finance_time_num;
                //分期的收益(整期收益,剩余收益)
                $lists_profit=array($d_profit/ 360* 30/100,$d_profit/ 360* 30/100);
                break;


            // case 'y':
           //     $lists_profit;
           //     break;
        }
        switch($this->repayment){

            //到期还本付息
            case 'sit':
                $month=0;
                break;

            //按月付息，到期还本
            case 'month':
                //还本金方式（分期的本金，最后一期的本金）
                $lists_capital=array('0',$money);
                break;

            //按月等额还本付息
            case 'profits_mode_three':
                //还本金方式（分期的本金，最后一期的本金）
                $lists_capital=array(round($money/$month,2,PHP_ROUND_HALF_DOWN),$money-($month-1)*round($money/$month,2,PHP_ROUND_HALF_DOWN));
                break;
            //先息后本
            case 'profit_money':
                $month=2;
                $lists_profit=array($profit,'0');
                $lists_capital=array('0',$money);
                break;
        }
        $lists['all']['profit'] = $profit;
        $lists['all']['capital'] = $money;
        $lists['all']['all'] = $lists['all']['profit'] + $lists['all']['capital'];
        if($month!=0){
            $i=0;
            for ($i; $i <$month-1; $i++) {
                //每月收益记录
                $lists[$i]['key'] = $i + 1;
                $lists[$i]['profit'] = $lists_profit['0'];
                $lists[$i]['capital'] =$lists_capital['0'];
                $lists[$i]['all'] = $lists[$i]['profit']+$lists[$i]['capital'];
            }
            $lists[$i]['key'] = $i + 1;
            $lists[$i]['profit'] = $lists_profit['1'];
            $lists[$i]['capital'] =$lists_capital['1'];
            $lists[$i]['all'] = $lists[$i]['profit']+$lists[$i]['capital'];
        }
        else{
            $lists['0']['key'] = 1;
            $lists['0']['capital'] =$money;
            $lists['0']['profit'] =$profit;
            $lists['0']['all'] = $lists['0']['profit'] + $lists['0']['capital'];
        }
        return $lists;
    }
    /**
     * @param array $lists
     * @return array
     */
    private function makeList(array $lists)
    {
        foreach ($lists as $key => $list) {
            if (is_array($list)) {
                $list=$this->makeList($list);
            } else {
                if($key!='key'){
                    $list = number_format($list, 2);
                }
            }
            $lists[$key]=$list;
        }
        return $lists;
    }
  /**
   * 判断项目是否达到满标的条件
   * @return [type] [description]
   */
  public function checkFull(){
    if($this->status=='payment' || $this->status=='fail'){return false;}
    //比例
    if($this->full_code=='pc' && $this->finance_money*$this->full_num/100<=$this->financed_money){
      return true;
    }
    //时间
    if($this->full_code=='time' && $this->full_num<=date('Y-m-d H:i:s')){
      return true;
    }
    //金额
    if($this->full_code=='money' && $this->full_num<=$this->financed_money){
      return true;
    }
    return false;
  }
  /**
   * 项目融资期限的总利息
   * @param  string $rate 利率,默认为项目的总利率
   * @return [type]       [description]
   */
  public function financeTime($rate,$financed_money=''){
    $money=0;
    if(empty($financed_money)){$financed_money=$this->financed_money;}
    $day_profit=$financed_money*$rate/100;//利润
    //天
    if($this->finance_time_cate=='d'){
      $money=$day_profit/360*$this->finance_time_num;
    }
    //月
    if($this->finance_time_cate=='m'){
      $money=$day_profit/360*$this->finance_time_num*30;
    }
    //自然月
    if($this->finance_time_cate=='mm'){
      $money=$day_profit/12*$this->finance_time_num;
    }
    return floor($money*100)/100;
  }
  /**
   * 查看可用的投资红包
   * @param  [type] $money      投资金额
   * @param  [type] $id         项目编号
   * @param  [type] $user_id    用户编号
   * @return [type]             红包记录
   */
  public static function getGift($money,$id,$user_id=null){
    if(empty($user_id)){
        $user=User::user();
    }else{
        $user=User::find($user_id);
    }
    $project=Projects::find($id);
    $result=GiftReceive::join('gift_activities', 'gift_activities.id', '=', 'gift_receives.activity_id')
    ->select('gift_receives.*','gift_activities.name')
    ->where('gift_receives.user_id',$user->id)
    ->whereNotIn('gift_activities.type_id',['gift_activity_type_2'])
    ->where('gift_receives.status',0)
    ->where(function ($query) use ($money) {
    // ->where('gift_activities.used_rule','gift_money_used_rule_1')
        $query->where('gift_activities.used_rule_money','<=',$money)
            ->orWhereNull('gift_activities.used_rule_money');
        })
    ;
    if($project->finance_time_cate!='mm'){
        $result->where('gift_activities.cate_id','<>','gift_activity_cate_register');
    }
    // if($cate!=0){
    //     $result=$result->where('gift_activities.cate_id',$cate);
    // }
    $result=$result->get();
    return $result;
  }
  /**
   * 录入sian标
   * @return [type] [description]
   */
  public function sina_project(){
    //预计还款的期限
    $term=time();
    //天
    if($this->finance_time_cate=='d'){
      $term=strtotime('+'.$this->finance_time_num.' day',$term);
    }
    //月
    if($this->finance_time_cate=='m'){
      $term=strtotime('+'.($this->finance_time_num*30).' day',$term);
    }
    //自然月
    if($this->finance_time_cate=='mm'){
      $term=strtotime('+'.$this->finance_time_num.' month',$term);
    }

    $financer=User::find($this->financier_id);//借款人
    $repay_method='';//还款方式
    if($this->repayment=='sit'){
      $repay_method='DEBT_MATURITY';
    }
    if($this->repayment=='month'){
      $repay_method='MONTHLY_PAYMENT';
    }
    //担保方式
    $guarantee_method='无担保';
    if($this->collateral_type=='collateral_type_1' && $this->collateral_type=='collateral_type_2'){
      $guarantee_method=$this->suretyCompany()->company_name;
    }
    //投资人列表
    // $investor_list=array();
    // $project_users=ProjectsUser::join('users','users.id','=','projects_user');
    $sina_data=[
      'goods_id'=>$this->sn,
      'goods_name'=>$this->projects_name,
      'annual_yield'=>$this->rate_search,
      'term'=>date('YmdHis',$term),
      'repay_method'=>$repay_method,
      'guarantee_method'=>$guarantee_method,
      'debtor_list'=>$financer->identity_id.'^UID^'.$this->finance_money,
      'investor_list'=>'',
      'total_amount'=>$this->finance_money,
      'begin_date'=>date('YmdHis',strtotime($this->start_time)),
      'url'=>'https://www.ibeibeili.com/oneProjects/'.$this->id,
    ];
    return CreateP2pHostingBorrowingTarget::send($sina_data);
  }
}